<?php
class AuthController extends Zend_Controller_Action
{

    public function  init() {
        $this->form = new Default_Form_Login();
    }

    public function indexAction()
    {
        /*
        $storage = new Zend_Auth_Storage_Session();
        $storage->clear();
        */
        $auth = Zend_Auth::getInstance();
        if(!Zend_Auth::getInstance()->hasIdentity()) {
            $this->_redirect('/auth/login');
        }
        $this->view->email = $user['email'];
    }

    public function loginAction()
    {
        //$this->form->setAttrib('redirect', $redirect );
        $auth = Zend_Auth::getInstance();
        if(Zend_Auth::getInstance()->hasIdentity()) {
            $this->_redirect('/index');
        } else if ($this->getRequest()->isPost()) {
            if ( $this->form->isValid($this->getRequest()->getPost()) ) {
                
                $result = $auth->authenticate(
                    new Default_Model_AuthAdapter(
                        $this->getRequest()->getPost('email'),
                        $this->getRequest()->getPost('pass')
                    )
                );
                if(!$result->isValid()) {
                    switch ($result->getCode()) {
                        case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID:
                            $this->view->message = 'Nepareizs lietotājvārds vai parole';
                    }
                } else {
                    //Successfully logged in
                    $this->_redirect('/index');
                }
            }
        }
        $this->view->message = $this->_getParam('message');
        //$this->view->form = $this->form;
    }

    public function signupAction()
    {
        $users = new Users();
        $form = new RegistrationForm();
        $this->view->form=$form;
        if($this->getRequest()->isPost()){
            if($form->isValid($_POST)){
                $data = $form->getValues();
                if($data['password'] != $data['confirmPassword']){
                    $this->view->errorMessage = "Password and confirm password don’t match.";
                    return;
                }
                if($users->checkUnique($data['email'])){
                    $this->view->errorMessage = "Name already taken. Please choose another one.";
                    return;
                }
                unset($data['confirmPassword']);
                $users->insert($data);
                $this->_redirect('auth/login');
            }
        }
    }


    public function logoutAction()
    {
        $auth = Zend_Auth::getInstance();
        $auth->clearIdentity();
        $this->_redirect('/');
    }

}